﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using static System.Web.Razor.Parser.SyntaxConstants;
using System.Web.Mvc;
using static StaticDemo.App_Start.ApplicationUserManager;

namespace StaticDemo.App_Start
{
    public static class ApplicationAuthenticationTypes
    {
        public const string ApplicationCookie = "vi_vh";
    }
    public class ApplicationUser : IdentityUser
    {
        public ClaimsIdentity ExternalIdentity { get; set; }
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // 请注意，authenticationType 必须与 CookieAuthenticationOptions.AuthenticationType 中定义的相应项匹配
            var userIdentity = await manager.CreateIdentityAsync(this, ApplicationAuthenticationTypes.ApplicationCookie);
            // 在此处添加自定义用户声明
            return userIdentity;
        }
    }
    public class ApplicationClaimsIdentityFactory : ClaimsIdentityFactory<ApplicationUser, string>
    {
        public override Task<ClaimsIdentity> CreateAsync(UserManager<ApplicationUser, string> manager, ApplicationUser user, string authenticationType)
        {
            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            ClaimsIdentity id = new ClaimsIdentity(authenticationType, this.UserNameClaimType, this.RoleClaimType);
            id.AddClaim(new Claim(this.UserIdClaimType, this.ConvertIdToString(user.Id), "http://www.w3.org/2001/XMLSchema#string"));
            id.AddClaim(new Claim(this.UserNameClaimType, user.UserName, "http://www.w3.org/2001/XMLSchema#string"));
            id.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"));
            if (manager.SupportsUserClaim && user.ExternalIdentity != null)
                user.ExternalIdentity.Claims.ToList().ForEach(claim =>
                {
                    if (!id.HasClaim(p => p.Type == claim.Type))
                        id.AddClaim(claim);
                });
            return Task.FromResult(id);
        }

    }
    // 配置此应用程序中使用的应用程序用户管理器。UserManager 在 ASP.NET Identity 中定义，并由此应用程序使用。
    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
            : base(store)
        {
            this.ClaimsIdentityFactory = new ApplicationClaimsIdentityFactory();
        }

        public override bool SupportsUserClaim
        {
            get
            {
                return true;
            }
        }

        public override bool SupportsUserLockout
        {
            get
            {
                return false;
            }
        }

        public override bool SupportsUserRole
        {
            get
            {
                return false;
            }
        }

        public override bool SupportsUserSecurityStamp
        {
            get
            {
                return false;
            }
        }

        public class ApplicationUserStore : UserStore<ApplicationUser>
        { 
            public ApplicationUserStore()
            {

            }

            public ApplicationUserStore(DbContext context)
                : base(context)
            {


            }
              
            public override Task<bool> GetEmailConfirmedAsync(ApplicationUser user)
            {
                return Task.FromResult(user.EmailConfirmed);
                //return base.GetEmailConfirmedAsync(user);
            }
            
        }
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
        {
            //var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

            var manager = new ApplicationUserManager(new ApplicationUserStore());

            //manager.PasswordHasher = new ApplicationPasswordHasher();

            // 配置用户名的验证逻辑
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail = true
            };

            // 配置密码的验证逻辑
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 8,
                RequireNonLetterOrDigit = true,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };

            // 配置用户锁定默认值
            manager.UserLockoutEnabledByDefault = false;
            manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;
            // 注册双重身份验证提供程序。此应用程序使用手机和电子邮件作为接收用于验证用户的代码的一个步骤
            // 你可以编写自己的提供程序并将其插入到此处。
            //manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider<ApplicationUser>
            //{
            //    MessageFormat = "你的安全代码是 {0}"
            //});
            //manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider<ApplicationUser>
            //{
            //    Subject = "安全代码",
            //    BodyFormat = "你的安全代码是 {0}"
            //});
            //manager.EmailService = new EmailService();
            //manager.SmsService = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }
    }

    public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
    { 
        public ApplicationSignInManager(IAuthenticationManager authenticationManager) : base(GetApplicationUserManager(), authenticationManager)
        {

        }

        public static ApplicationUserManager GetApplicationUserManager()
        { 
            return new ApplicationUserManager(new ApplicationUserStore()); 
        }
   
   
    }
  
}